import os
import glob
import pickle
from . import game_data
from operator import itemgetter

#
# list of save file data, contains dicts with name, path and time
#
saves = []

#
# scan the saves folder for files ending in ".sav" and then
# read the header data to get the save name and timestamp
#
# we could probably get the timestamp from the OS
# but this way I don't need to worry about cross platform nonsense
#
def scan():
	global saves
	list = []
#
#	loop over all the save files in the saves folder
#
	for file in glob.glob("saves/*.sav"):
		print "file = ", file
#
#		unpickle the header
#
		d = {}
		with open(file, "rb") as fd:
			d = pickle.load(fd)
#
#		add the header to the list
#
		list += [ d ]
#
#	make the global save list point at the scan results
#
	saves = sorted(list, key = itemgetter("stamp"), reverse=True)

def count():
	return len(saves)

def get_name_from_index(index):
	return saves[index]["name"]

def load_from_index(index):
	return load_from_file(saves[index]["file"])

def load_from_file(file):
	print "loading from file '{}'".format(file)
	if game_data.load(file):
		print "*********************************************"
		game_data.data.print_it()
		print "*********************************************"
		return True
	print "load failed"
	return False

def save_filename():
	import re
#
#	I never much liked the idea of saving using
#	brothel zero's name as the file name
#
#	but it'll do for now. 
#
#	formatting this to make sure it's a string and not a QString
#
	name = "{}".format( game_data.data.brothels[0].name )
	print "formatting ", name
#
#	squash any potentially problematic chars in the name
#
	exp = "[^A-Za-z0-9 ]"
	s1 = re.sub(exp, "", name)
	s2 = re.sub(" ", "_", s1)
	name = s2
#
#	now add the folder and the extension
#
	filename = "saves/{}.sav".format(name)
#
#	and return the string
#
	return filename

def save_game():
	filename = save_filename()
	print "SAVING"
	game_data.data.print_it()
	game_data.save(filename)
	print "SAVE DONE"
	scan()




scan()
